package com.ljm.lock.autoconfigure;

import com.ljm.lock.properties.LockProperties;
import com.ljm.lock.service.ILockService;
import com.ljm.lock.service.impl.RedisLockServiceImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

/**
 * @Author: ChenHuaMing
 * @Date: 2020/10/9 10:42
 * @Description: 分布式锁使用lua配置
 */
@Configuration
@EnableConfigurationProperties(value = LockProperties.class)
public class LockConfiguration {
    private final ApplicationContext applicationContext;

    public LockConfiguration(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ILockService lockService(LockProperties lockProperties){
        switch (lockProperties.getType()){
            case "redis":
                return new RedisLockServiceImpl(this.getRedisTemplate(),this.redisScript(),lockProperties.getTimeOut());
                default:
                    return null;
        }
    }

    private StringRedisTemplate getRedisTemplate() {
        StringRedisTemplate bean = (StringRedisTemplate) this.applicationContext.getBean("stringRedisTemplate");
        if(null==bean){
            bean=new StringRedisTemplate();
        }
        return bean;
    }

    private DefaultRedisScript<Boolean> redisScript(){
        DefaultRedisScript<Boolean> defaultRedisScript=new DefaultRedisScript<>();
        defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/redisLock.lua")));
        defaultRedisScript.setResultType(Boolean.class);
        return defaultRedisScript;
    }

}
